package com.castle.fortress.admin.dify.util;

import com.castle.fortress.admin.dify.model.entity.DifyApiConfig;
import com.castle.fortress.admin.dify.model.enums.DifyConfigTypeEnum;
import com.castle.fortress.admin.dify.service.DifyApiConfigService;
import io.github.imfangs.dify.client.DifyChatflowClient;
import io.github.imfangs.dify.client.DifyClientFactory;
import io.github.imfangs.dify.client.enums.ResponseMode;
import io.github.imfangs.dify.client.exception.DifyApiException;
import io.github.imfangs.dify.client.model.DifyConfig;
import io.github.imfangs.dify.client.model.chat.ChatMessage;
import io.github.imfangs.dify.client.model.chat.ChatMessageResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;

@Service
@Slf4j
public class DifyUtil {

    @Resource
    private DifyApiConfigService difyApiConfigService;
    private DifyChatflowClient chatFlowClient;

    /**
     * 初始化Dify客户端
     */
    @PostConstruct
    public void init() {
        try {
            reloadConfig();
            log.info("Dify客户端初始化成功");
        } catch (Exception e) {
            log.error("Dify客户端初始化失败", e);
        }
    }

    /**
     * 重新加载配置
     * 当数据库中的配置更新后，可以调用此方法重新加载配置
     */
    public void reloadConfig() {
        try {
            // 从数据库获取配置信息
            DifyApiConfig config = difyApiConfigService.getConfigByType(DifyConfigTypeEnum.INFORMATION);
            String baseUrl = config.getBaseUrl();
            String apiKey = config.getApiKey();
            Integer connectTimeout = config.getConnectTimeout();
            Integer readTimeout = config.getReadTimeout();
            Integer writeTimeout = config.getWriteTimeout();

            DifyConfig difyConfig = DifyConfig.builder()
                    .apiKey(apiKey)
                    .baseUrl(baseUrl)
                    .connectTimeout(connectTimeout)
                    .writeTimeout(writeTimeout)
                    .readTimeout(readTimeout)
                    .build();

            chatFlowClient = DifyClientFactory.createClient(difyConfig);
        } catch (Exception e) {
            log.error("重新加载Dify配置失败", e);
        }
    }

    public String sendChatMessageSync(String query, String user, String conversationId) {
        try {
            // 创建聊天消息
            ChatMessage.ChatMessageBuilder messageBuilder = ChatMessage.builder()
                    .query(query)
                    .user(user)
                    .responseMode(ResponseMode.BLOCKING);

            // 如果有会话ID，则设置
            if (conversationId != null && !conversationId.trim().isEmpty()) {
                messageBuilder.conversationId(conversationId);
            }

            ChatMessage message = messageBuilder.build();

            // 发送消息并获取响应
            ChatMessageResponse response = chatFlowClient.sendChatMessage(message);

            log.info("聊天消息发送成功: user={}, conversationId={}, messageId={}",
                    user, response.getConversationId(), response.getMessageId());

            return response.getAnswer();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发送聊天消息失败: user={}, query={}", user, query);
            return null;
        }
    }
}
